package com.example.jdbc0914.dao;
import com.example.jdbc0914.dao.DBUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：lqs
 * @date ：Created in 2023/9/14 14:39
 * @description：
 * @modified By：
 * @version:
 */
public class BaseDao {


    public List<Map<String, Object>> querySQL(String sql, Object... params) {

        //注册驱动、获取连接
        Connection connection = DBUtil.getConnection();
        PreparedStatement pre = null;
        ResultSet resultSet = null;
        try {
            //赋值prepareStatement对象
            pre = connection.prepareStatement(sql);
            //将占位符赋值
            if (pre != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    pre.setObject(i + 1, params[i]);
                }
            }
            //执行sql
            resultSet = pre.executeQuery();
            //操作结果集
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            List<Map<String, Object>> list = new ArrayList<>();
            while (resultSet.next()) {
                Map<String, Object> map = new HashMap<>();
                //获取一行数据
                for (int i = 1; i <= columnCount; i++) {
                    //获取列名和列数据
                    String columnName = metaData.getColumnName(i);
                    Object object = resultSet.getObject(columnName);
                    map.put(columnName, object);
                }
                list.add(map);
            }
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            DBUtil.closeConnection(connection, pre, resultSet);
        }
        return null;
    }

    /**
     * @param sql
     * @param params
     * @return boolean
     * @description: 更新、插入、删除
     * @create time 2023/8/30 15:08
     */
    public boolean updateSQL(String sql, Object... params) {

        Connection connection = null;
        PreparedStatement pre = null;
        try {
            //注册驱动、获取连接
            connection = DBUtil.getConnection();
            //赋值prepareStatement对象
            pre = connection.prepareStatement(sql);
            //将占位符赋值
            if (pre != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    pre.setObject(i + 1, params[i]);
                }
            }
            //执行sql
            assert pre != null;
            int i = pre.executeUpdate();
            //操作结果集
            if (i > 0) {
                return true;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭连接
            DBUtil.closeConnection(connection, pre, null);
        }
        return false;
    }
}

